package com.cloud.mall.conf.gateway;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author: 梁二东
 * @Date: 2024/12/8 10:14
 * @Description:
 **/
@Component
@Slf4j
public class QueryParamGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取uri对象
        URI uri = request.getURI();
        log.info("uri: {}", uri);
        String path = request.getURI().getPath();
        log.info("path: {}", path);
        String query = request.getURI().getQuery();
        log.info("url参数: {}", query);

        // 获取请求参数转换成键值对，值是一个数组
//        MultiValueMap<String, String> multiQueryParams = request.getQueryParams();
//        log.info("获取请求参数转换成键值对 multiQueryParams = {}", multiQueryParams);
        // 将query参数转换成键值对，值是一个字符串，hutool包的HttpUtil
        Map<String, String> queryParams = HttpUtil.decodeParamMap(query, StandardCharsets.UTF_8);
        log.info("将queryUrl参数转换成键值对: {}", queryParams);

//        // 处理uri，通过?分割，下标第0位是请求地址，第1位置是请求参数
//        String url = uri.toString();
//        String[] urlSplit = url.split("\\?");
//        // 拼接新的url 这里自己处理即可，我这里直接替换请求参数
//        String newUrl = urlSplit[0] + "?" + "name=kerwinNew&age=17";
//        URI newUri = null;
//        try {
//            //将编码后的 %23 替换为 ，重新用这个字符串生成 URI
//            newUri = new URI(newUrl.replace("%23", ""));
//        } catch (URISyntaxException e) {
//            throw new RuntimeException(e);
//        }
//        ServerHttpRequest mutableReq = request.mutate()
//                .uri(newUri)
//                .build();

        ServerHttpRequest mutableReq = request.mutate()
                .uri(uri)
                .build();

        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);

    }

    @Override
    public int getOrder() {
        return -1000;
    }
}
